package study.util;

import com.alibaba.fastjson.JSONObject;
import org.springframework.http.*;
import org.springframework.util.DigestUtils;
import org.springframework.web.client.RestTemplate;


public class CodeService {

    String gateway =  "api-gateway.jd.com";
    public static final String GEN_SCOPE_CODE_URL = "/jacp-security/security/api/sso/user/sunxuejian/scope/sys/permission";
    String appId = "jcase";
    String appSecret = "1d64874d-8319-4b14-9182-eb5eaf11cd8b";


    public String genSpaceScopeCode(Integer code) {

        RestTemplate restTemplate = new RestTemplate();

        JSONObject param = new JSONObject();
        HttpEntity<JSONObject> request = new HttpEntity<>(param, genHeaders());

        String url = String.format("%s%s", gateway, GEN_SCOPE_CODE_URL);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, request, String.class);
        JSONObject responseBody = JSONObject.parseObject(response.getBody());
        Integer statusCode = responseBody.getInteger("code");
        if (HttpStatus.OK.value() != statusCode) {
//            logger.warn("获取scopeCode失败！");
            System.out.println("获取scopeCode失败！");
            return null;
        }

        return responseBody.toJSONString();
//        SecScope scope = new SecScope();
//        scope.setScopeCode(responseBody.getString("data"));
//        scope.setType(SPACE);
//        scope.setCode(code);
//        scopeService.insert(scope);
//
//        return scope.getScopeCode();
    }

    private HttpHeaders genHeaders() {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.add("appId", appId);
        Long timestamp = System.currentTimeMillis();
        headers.add("timestamp", String.valueOf(timestamp));
        headers.add("signature", getSignature(timestamp));
//        headers.add("optErp", userHelper.getCurrentUserErp());

        return headers;
    }

    private String getSignature(Long timestamp) {
//签名的明文信息，由应用编码、时间戳、和密钥顺序拼接组成
        String plainText = appId + timestamp + appSecret;
//生成的签名
        String signature = DigestUtils.md5DigestAsHex(plainText.getBytes());
        return signature;
    }
}
